﻿using Furion;
using Furion.DependencyInjection;
using Furion.DynamicApiController;
using Mapster;
using Microsoft.AspNetCore.Mvc;
using NiuPi.Database.Platform;
using NiuPi.Tools;
using SqlSugar;

namespace NiuPi.Platform.Services
{
    /// <summary>
    /// 角色管理模块
    /// </summary>
    [Route("api/platform/[controller]")]
    [ApiDescriptionSettings("platform")]
    public class RoleService : IDynamicApiController, ITransient
    {
        private readonly ILogger<RoleService> Logger;
        private readonly SqlSugarScope Db;
        public RoleService(ILogger<RoleService> _Logger, SqlSugarScope _Db)
        {
            Logger = _Logger;
            Db = _Db;
        }
        /// <summary>
        /// 添加角色
        /// </summary>
        /// <param name="input"></param>
        /// <returns></returns>
        [HttpPost]
        public async Task<IActionResult> Add(Role input)
        {
            var model = input.Adapt<Role>();
            var isOk = 0;
            var result = await Db.UseTranAsync(async () =>
             {
                await Db.Insertable(model).AddSubList(it => it.Permissions.First().RoleId).ExecuteCommandAsync();
             });
            if (result.IsSuccess)
            {
                return RestfulResult.Instance.OnSucceeded();
            }
            else
            {
                return RestfulResult.Instance.OnFailed();
            }
        }
        /// <summary>
        /// 编辑角色信息
        /// </summary>
        /// <param name="input"></param>
        /// <returns></returns>
        [HttpPost]
        public async Task<IActionResult> Edit(Role input)
        {
            //自动将前端参数映射到模型
            var model = input.Adapt<Role>();
            //db.Ado.BeginTran//单库
            //db.BeginTran //多库
            var isOk = 0;
            var result = await Db.UseTranAsync(async () =>
            {
                isOk=await Db.Deleteable<RolePermission>().Where(x => x.RoleId == input.Id).ExecuteCommandAsync();
                isOk = await Db.Updateable(input).ExecuteCommandAsync();
                isOk = await Db.Insertable(input.Permissions).ExecuteCommandAsync();
            });
            if (result.IsSuccess & isOk > 0)
            {
                return RestfulResult.Instance.OnSucceeded();
            }
            else
            {
                return RestfulResult.Instance.OnFailed();
            }
        }
        /// <summary>
        /// 根据ID删除角色信息
        /// </summary>
        /// <param name="id"></param>
        /// <returns></returns>
        [HttpGet]
        public async Task<IActionResult> Del(int id)
        {
            var isOk = 0;
            var result = await Db.UseTranAsync(async () =>
            {
                isOk= await Db.Deleteable<Role>(id).ExecuteCommandAsync();
                isOk=await Db.Deleteable<RolePermission>().Where(x => x.RoleId == id).ExecuteCommandAsync();
            });
            if (result.IsSuccess&& isOk>0)
            {
                return RestfulResult.Instance.OnSucceeded();
            }
            else
            {
                return RestfulResult.Instance.OnFailed();
            }
        }
        /// <summary>
        /// 根据ID查询角色信息查询
        /// </summary>
        /// <param name="id"></param>
        /// <returns></returns>
        public async Task<IActionResult> GetOne(int id)
        {
            var model = await Db.Queryable<Role>()
                .Mapper(it => it.Permissions, it => it.Permissions.First().RoleId)
                .FirstAsync(x => x.Id == id);
            if (model.Id > 0)
            {
                return RestfulResult.Instance.OnSucceeded(model);
            }
            else
            {
                return RestfulResult.Instance.OnFailed();
            }
        }
        /// <summary>
        /// 查询角色列表
        /// </summary>
        /// <param name="pageIndex">当前页</param>
        /// <param name="pageSize">每页数量</param>
        /// <returns></returns>
        public async Task<IActionResult> GetList(int pageIndex = 0, int pageSize = 10)
        {
            RefAsync<int> totalCount = 0;
            var result = await Db.Queryable<Role>().Mapper(it => it.Permissions, it => it.Permissions.First().RoleId).ToPageListAsync(pageIndex, pageSize, totalCount);
            var totalPages = (int)Math.Ceiling(totalCount / (double)pageSize);
            return RestfulResult.Instance.OnPageSucceeded(
                new PageResult<Role>
                {
                    PageNo = pageIndex,
                    PageSize = pageSize,
                    Rows = result.ToList(),
                    TotalRows = totalCount,
                    TotalPage = totalPages
                },
            App.HttpContext.Request.Headers
            );
        }
    }
}
